//
//  KLBookService.m
//  KLBookStore
//
//  Created by apple on 2017/10/15.
//  Copyright © 2017年 NetEaseExam. All rights reserved.
//

#import "KLBookService.h"

#import "KLBookEntityDAO.h"
#import "KLBookTagDAO.h"
#import "KLBookAuthorDAO.h"
#import "KLBookTranslatorDAO.h"
#import "KLBookDBHelper.h"

@implementation KLBookService

+ (dispatch_queue_t)serviceQueue {
    static dispatch_queue_t service_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service_queue = dispatch_queue_create("book.service.list", DISPATCH_QUEUE_SERIAL);
    });
    return service_queue;
}

+ (long long)favorBook:(KLBookEntity *)bookEntity {
    FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
    if (![db open]) {
        return 0;
    }
    
    long long bookId = [KLBookEntityDAO insertModel:bookEntity withDataBase:db];
    
    if (bookId == 0) {
        return 0;
    }
    
    [bookEntity.authors enumerateObjectsUsingBlock:^(KLBookAuthor* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.bookId = bookId;
        [KLBookAuthorDAO insertModel:obj withDataBase:db];
    }];
    [bookEntity.translators enumerateObjectsUsingBlock:^(KLBookTranslator * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.bookId = bookId;
        [KLBookTranslatorDAO insertModel:obj withDataBase:db];
    }];
    [bookEntity.tags enumerateObjectsUsingBlock:^(KLBookTag * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.bookId = bookId;
        [KLBookTagDAO insertModel:obj withDataBase:db];
    }];
    
    [db close];
    
    return bookId;
    
}

+ (void)favorBook:(KLBookEntity *)bookEntity completion:(void (^)(long long))completionHandler {
    
    dispatch_async([[self class] serviceQueue], ^{
        FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
        if (![db open]) {
            if (completionHandler) {
                completionHandler(0);
            }
        }
        
        long long bookId = [KLBookEntityDAO insertModel:bookEntity withDataBase:db];
        
        if (bookId == 0) {
            completionHandler(0);
        }
        
        [bookEntity.authors enumerateObjectsUsingBlock:^(KLBookAuthor* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.bookId = bookId;
            [KLBookAuthorDAO insertModel:obj withDataBase:db];
        }];
        [bookEntity.translators enumerateObjectsUsingBlock:^(KLBookTranslator * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.bookId = bookId;
            [KLBookTranslatorDAO insertModel:obj withDataBase:db];
        }];
        [bookEntity.tags enumerateObjectsUsingBlock:^(KLBookTag * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.bookId = bookId;
            [KLBookTagDAO insertModel:obj withDataBase:db];
        }];
        
        [db close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler(bookId);
            }
        });
    });
}

+ (BOOL)deleteBookWithId:(long long)localId {
    FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
    if (![db open]) {
        return NO;
    }
    BOOL entitySuc = [KLBookEntityDAO deleteModelWithId:localId withDataBase:db];
    BOOL authorSuc = [KLBookAuthorDAO deleteModelWithId:localId withDataBase:db];
    BOOL translatorSuc = [KLBookTranslatorDAO deleteModelWithId:localId withDataBase:db];
    BOOL tagSuc = [KLBookTagDAO deleteModelWithId:localId withDataBase:db];
    
    [db close];
    
    return entitySuc;
}

+ (void)deleteBookWithId:(long long)localId completion:(void (^)(BOOL))completionHandler {
    dispatch_async([[self class] serviceQueue], ^{
        FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
        if (![db open]) {
            if (completionHandler) {
                completionHandler(NO);
            }
        }
        
        BOOL entitySuc = [KLBookEntityDAO deleteModelWithId:localId withDataBase:db];
        BOOL authorSuc = [KLBookAuthorDAO deleteModelWithId:localId withDataBase:db];
        BOOL translatorSuc = [KLBookTranslatorDAO deleteModelWithId:localId withDataBase:db];
        BOOL tagSuc = [KLBookTagDAO deleteModelWithId:localId withDataBase:db];
        
        [db close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler(entitySuc);
            }
        });
    });
}

+ (KLBookEntity *)searchFavoredBookWithDoubanId:(long long)doubanId {
    FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
    if (![db open]) {
        return 0;
    }
    
    KLBookEntity *book = [KLBookEntityDAO queryModelByDoubanId:doubanId withDataBase:db];
    
    [db close];
    return book;
    
}

+ (void)searchFavoredBookWithDoubanId:(long long)doubanId completion:(void (^)(KLBookEntity *))completionHandler {
    dispatch_async([[self class] serviceQueue], ^{
        FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
        if (![db open]) {
            if (completionHandler) {
                completionHandler(0);
            }
        }
        
        KLBookEntity *book = [KLBookEntityDAO queryModelByDoubanId:doubanId withDataBase:db];

        [db close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler(book);
            }
        });
    });
}

+ (NSArray<KLBookEntity *> *)getAllBookEntities {
    
    FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
    if (![db open]) {
        return 0;
    }
    
    NSArray *books = [KLBookEntityDAO queryAllModelsWithDataBase:db];
    for (KLBookEntity *book in books) {
        book.authors = [KLBookAuthorDAO queryModelById:book.id withDataBase:db];
        book.tags = [KLBookTagDAO queryModelById:book.id withDataBase:db];
        book.translators = [KLBookTranslatorDAO queryModelById:book.id withDataBase:db];
    }
    
    [db close];
    
    return books;
}

+ (void)getAllBookEntitiesWithCompletion:(void (^)(NSArray<KLBookEntity *> *))completionHandler {
    dispatch_async([[self class] serviceQueue], ^{
        FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
        if (![db open]) {
            if (completionHandler) {
                completionHandler(@[]);
            }
        }
        
        NSArray *books = [KLBookEntityDAO queryAllModelsWithDataBase:db];
        for (KLBookEntity *book in books) {
            book.authors = [KLBookAuthorDAO queryModelById:book.id withDataBase:db];
            book.tags = [KLBookTagDAO queryModelById:book.id withDataBase:db];
            book.translators = [KLBookTranslatorDAO queryModelById:book.id withDataBase:db];
        }
        
        [db close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler(books);
            }
        });
    });
}

+ (NSArray<KLBookEntity *> *)getBookEntitiesWithOffset:(long long)offset pageSize:(NSUInteger)size {
    
    FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
    if (![db open]) {
        return 0;
    }
    
    NSArray *books = [KLBookEntityDAO queryModelsWithDataBase:db offset:offset pageSize:size];
    for (KLBookEntity *book in books) {
        book.authors = [KLBookAuthorDAO queryModelById:book.id withDataBase:db];
        book.tags = [KLBookTagDAO queryModelById:book.id withDataBase:db];
        book.translators = [KLBookTranslatorDAO queryModelById:book.id withDataBase:db];
    }
    
    [db close];
    
    return books;
}

+ (void)getBookEntitiesWithOffset:(long long)offset pageSize:(NSUInteger)size completion:(void (^)(NSArray<KLBookEntity *> *))completionHandler {
    dispatch_async([[self class] serviceQueue], ^{
        FMDatabase *db = [FMDatabase databaseWithPath:[KLBookDBHelper dbPath]];
        if (![db open]) {
            if (completionHandler) {
                completionHandler(@[]);
            }
        }
        
        NSArray *books = [KLBookEntityDAO queryModelsWithDataBase:db offset:offset pageSize:size];
        for (KLBookEntity *book in books) {
            book.authors = [KLBookAuthorDAO queryModelById:book.id withDataBase:db];
            book.tags = [KLBookTagDAO queryModelById:book.id withDataBase:db];
            book.translators = [KLBookTranslatorDAO queryModelById:book.id withDataBase:db];
        }
        
        [db close];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionHandler) {
                completionHandler(books);
            }
        });
    });
}

@end
